package com.bangcommunity.bbframe.http.resttemplate;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author tanghc
 * @date 18/7/2
 */
public class RestTemplateUtil {
    static Logger logger = LoggerFactory.getLogger(RestTemplateUtil.class);
    public static RestTemplate createRestTemplate() {
        RestTemplate restTemplate = new RestTemplate(createOkHttp3ClientHttpRequestFactory());
        return restTemplate;
    }
    private static OkHttp3ClientHttpRequestFactory createOkHttp3ClientHttpRequestFactory(){
        OkHttp3ClientHttpRequestFactory okHttp3ClientHttpRequestFactory = new OkHttp3ClientHttpRequestFactory(createClient());
        okHttp3ClientHttpRequestFactory.setConnectTimeout(5000);
        okHttp3ClientHttpRequestFactory.setReadTimeout(5000);
        okHttp3ClientHttpRequestFactory.setWriteTimeout(5000);
        return okHttp3ClientHttpRequestFactory;
    }
    private static OkHttpClient createClient(){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(s -> logger.info(s));
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(httpLoggingInterceptor);
        return builder.build();
    }

    public static void main(String[] args) {
        RestTemplate restTemplate = RestTemplateUtil.createRestTemplate();

    }
}
